//
//  WPMainViewController.swift
//  WB
//
//  Created by 汪鹏 on 2016/12/14.
//  Copyright © 2016年 汪鹏. All rights reserved.
//

import UIKit
import SVProgressHUD

private let VERSION = "version"
/// 主控制器
class WPMainViewController: UITabBarController {

    
    /// 懒加载撰写按钮
    lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    
    /// 定时器
    private var timer:Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        
        setupComposeButton()
        
        setUpTimer()
        
        setNewFeatureOrWelcomeView()
        
        delegate = self
        
        // 监听用户登陆的通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: USERSHOULDLOGINNOTIFICATION), object: nil)
        
    }
    
    
    /// 设置设备方向
    /// - 使用代码控制设备的方向，好处是可以在需要横屏的时候，单独处理
    /// - 设置支持的方向之后，当前的控制器及子控制器都会遵守这个方向
    /// - 如果是播放视频，通常是 modal 展现的！
    override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
        return .portrait
    }
    
    override var shouldAutorotate: Bool{
        return false
    }
    
    override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }

    
    /// 撰写按钮的点击事件
    ///
    /// @objc的作用：允许这个函数在运行时通过oc的消息机制被访问
    @objc private func composeButtonClick(button:UIButton){
        
        let composeView = WPComposeTypeView.composeView()
        
        composeView.show{[unowned composeView] (classname) in
            
             guard let vcName = NSClassFromString(Bundle.main.namespace+"."+classname) as? UIViewController.Type else{
            
                return
            }
            
            let vc = vcName.init()
            
            let nav = UINavigationController(rootViewController: vc)
            
            self.present(nav, animated: true, completion: {
                
                composeView.removeFromSuperview()
            })
            
        }

    }
    
    /// 设置撰写按钮
    private func setupComposeButton(){
        tabBar.addSubview(composeButton)
        
        let w = tabBar.bounds.width / CGFloat(childViewControllers.count)
        
        //composeButton.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        composeButton.frame = CGRect(x: 2*w, y: 0, width: composeButton.bounds.width, height: composeButton.bounds.height)
        
        composeButton.addTarget(self, action: #selector(composeButtonClick), for: .touchUpInside)
    }
    
    /// 设置所有的字控制器
    private func setupChildControllers(){
        
        // 从沙盒获取main.json文件
        let home_path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        
        // 拼接文件路径
        let file_path = (home_path as NSString).appendingPathComponent("main2.json")
    
        
        var data = NSData(contentsOfFile: file_path)
        
        if data == nil { // 如果data为nil表示从服务器没有请求到数据，就用bundle重的main.json
            
            // 从bundle加载文件
            let pathResource = Bundle.main.path(forResource: "main", ofType: "json")
            
            data = NSData(contentsOfFile: pathResource!)
        }
        
        // 反序列化获取到的文件
        guard let array = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [[String:Any]] else{
            return
        }
        
        /// 数据
        /*
         let array = [
            ["clsName":"WPHomeViewController","title":"首页","imageName":"home",
             "visitorInfor":["imageName":"","message":"关注一些人，回这里看看有什么惊喜"]
             ],
            ["clsName":"WPMessageViewController","title":"消息","imageName":"message_center",
             "visitorInfor":["imageName":"visitordiscover_image_message","message":"登陆后，别人评论你的微博，发给你的消息，都会在这里收到通知"]
             ],
            ["clsName":"xxxx"],
            ["clsName":"WPDiscoverViewController","title":"发现","imageName":"discover",
             "visitorInfor":["imageName":"visitordiscover_image_message","message":"登陆后，最新、最热微博尽在掌握，不会再于实事潮流擦肩而过"]
             ],
            ["clsName":"WPProfileViewController","title":"我的","imageName":"profile",
             "visitorInfor":["imageName":"visitordiscover_image_profile","message":"登陆后,回这里看看有什么惊喜"]
             ]
        ]
         
         */
        
        /*
        // 将数组写入沙盒
        (array as NSArray).write(toFile: "/Users/wangpeng/Desktop/main.json", atomically: true)
        
        // 数组 -> 序列化
        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        
        (data as NSData).write(toFile: "/Users/wangpeng/Desktop/main.json", atomically: true)
        */
        
        var arrayM = [UIViewController]()
        for dict in array {
            arrayM.append(controller(dict: dict))
        }
        
        /// 设置所有的控制器
        viewControllers = arrayM
        
    }
    
    
    /// 适用字典创建一个子控制器
    ///
    /// - Parameter dict: 给控制器的属性赋值
    /// - Returns: 返回一个控制器
    private func controller(dict:[String:Any]) -> UIViewController{
        
        
        /// 取得字典的值
        guard let clsName = dict["clsName"] as? String,
             let title = dict["title"] as? String,
             let imageName = dict["imageName"] as? String,
             let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WPBaseViewController.Type,
             let visitorInfor = dict["visitorInfor"] as? [String:String]   else {
                return UIViewController()
        }
        
        
        /// 创建试图控制器
        let vc = cls.init()
        vc.visitorData = visitorInfor
        vc.title = title
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 14)], for: .normal)
        let nav = WPNavigationViewController(rootViewController: vc)
        return nav
    }


    /// 设置定时器相关
    private func setUpTimer() {
        
        if !WPNetManager.shareManager.userLogon {
            return
        }
        
        timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(updateUnReadStatusCount), userInfo: nil, repeats: true)
        
    }
    
    /// 用户登陆通知方法
    @objc private func userLogin(n: NSNotification){
        
        // 关闭获取未读的微博数据定时器
        if timer?.isValid == true {
            
            timer?.invalidate()
        }
        
        var disPatchTime = DispatchTime.now()
        
        if n.object != nil { // token 过期
            
            SVProgressHUD.setDefaultMaskType(.gradient)
            
            SVProgressHUD.showInfo(withStatus: "您的登陆时间过长,请重新登陆!")
            
            disPatchTime = DispatchTime.now() + 2.5
            
        }
        
        DispatchQueue.main.asyncAfter(deadline: disPatchTime) {
            
            SVProgressHUD.setDefaultMaskType(.clear)
            
            let oAuthVC = UINavigationController(rootViewController: WPOAuthViewController())
            
            self.present(oAuthVC, animated: true, completion: nil)
                        
        }
    
    }
    
    /// 定时器方法
    @objc private func updateUnReadStatusCount() {
      
        // print(#function+"---获取未读微博数量定时器开启中")
        
        if !WPNetManager.shareManager.userLogon {
            return
        }
        
        WPNetManager.shareManager.getUnReadStatusCount{ (count) -> () in
            
            // 设置badgeValue
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            // 设置applicationIconBadgeNumber， ios8之后要用户授权才能显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }

    /// 控制器销毁调用，类似于oc的dealloc方法
    deinit {
        
        // 销毁定时器
        timer?.invalidate()
        
        // 销毁通知
        NotificationCenter.default.removeObserver(self)
    }
    
}


/// extension 类似于oc中的分类，在swift还可以用来切分代码块，可以把相近功能的函数放在一个extension便于代码维护,不能定义属性

// MARK:--UITabBarControllerDelegate
extension WPMainViewController:UITabBarControllerDelegate{
    
    
        /// 将要选择的tabBarItem
        ///
        /// - Parameters:
        ///   - tabBarController: tabBarController
        ///   - viewController: 目标控制器
        /// - Returns: 是否切换到目标控制器
        func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
            
            // 多次点击首页让首页滚动到顶部
            let index = (childViewControllers as NSArray).index(of: viewController)
            
            // 如果上次选中的和当前的选中的控制器相同，就让首页滚动到顶部
            if selectedIndex == 0 && index == selectedIndex {
                
                let nav = viewController as! WPNavigationViewController
                
                let vc = nav.childViewControllers[0] as! WPHomeViewController
                
                // 让tableView发生滚动
                vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
                
                // 延迟一秒，为了让tableView滚动完成才加载数据
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                    vc.loadData()
                })
                
                vc.tabBarItem.badgeValue = nil
                
                UIApplication.shared.applicationIconBadgeNumber = 0
            }
            
            return !viewController.isMember(of: UIViewController.self)

        }
    
    }



// MARK:--设置新特性、欢迎界面
extension WPMainViewController {
    
    func setNewFeatureOrWelcomeView() {
        
        let vi = isNewVersion ? WPNewFeatureView.newFeatureView() : WPWelcomeView.welcomeView()
        
        view.addSubview(vi)
        
    }
    
    /// extension 中可以有计算型属性，不会占用内存，类似于getter方法
    /// 构造函数给属性分配内存空间
    private var isNewVersion:Bool { //  新版本判断逻辑的实现
    
        // 1. 取得当前app的版本
        let app_version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        // 2. 取得偏好设置保存的版本
        let pre_version = UserDefaults.standard.object(forKey: VERSION) as? String ?? ""
        // 3. 将当前版本保存到偏好设置
        UserDefaults.standard.set(app_version, forKey: VERSION)
        // 4. 比较两个版本
        return app_version != pre_version
    }
}
